<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图主题信息 -->
    <el-card style="width:100%">
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoodsForm"
        ref="addGoodsFormRef"
        :rules="addGoodsFormRules"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          @tab-click="handleClick"
          :before-leave="beforeTabLeave"
        >
          <!-- 基本信息的tab-pane -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input
                v-model="addGoodsForm.goods_name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                placeholder="请输入"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                placeholder="请输入"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                placeholder="请输入"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="cateList"
                v-model="addGoodsForm.goods_cat"
                @change="handleChange"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children'
                }"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyCateDate"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item"
                  v-for="item in item.attr_vals"
                  :key="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyCateDate"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :headers="headersObj"
              :action="upLoadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :multiple="true"
              accept="image/png, image/jpeg"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce" />
            <el-button class="btnMarginTop" type="primary" @click="addGoods()"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 点击图名名称预览图片的dialog -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewImgDialogVisible"
      @close="previewImgDialogVisible = false"
    >
      <img :src="previewPath" alt="预览图片" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // el-steps进度条激活项,同时是el-tabs的vmodel(0,1,2...)
      activeIndex: '0',
      addGoodsForm: {
        goods_name: '',
        // 分类以逗号分隔{一级分类id,二级分类id,三级分类id}
        // 先测试用，后面删空，_cat
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        // 商品参数(包括动态参数，好静态属性)manyCateDate.attr_vals+onlyCateDate.attr_vals
        attrs: []
      },
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
        goods_price: [{ required: true, message: '商品价格不能为空', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '商品重量不能为空', trigger: 'blur' }],
        goods_number: [{ required: true, message: '商品数量不能为空', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 商品分类信息
      cateList: [],
      // 根据分类id获取到的商品参数(many)信息
      manyCateDate: [],
      onlyCateDate: [],
      upLoadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 点击图片名称预览大图，大图的网络路径
      previewPath: '',
      previewImgDialogVisible: false
    }
  },
  created () {
    this.getGoodsCate()
  },
  computed: {
    // 三级分类id
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // tabs标签切换
    async handleClick (tab, event) {
      //   this.activeIndex = tab.paneName
      // 商品参数
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        } else {
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ===
              '' ? [] : item.attr_vals.split(',')
          })
          this.manyCateDate = res.data
        }
      }
      // 商品属性sel=only
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        } else {
          this.onlyCateDate = res.data
        }
      }
    },
    // 获取商品分类信息
    async getGoodsCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.cateList = res.data
      }
    },
    handleChange (value) {
      // value和this.selectedKeys相同
      if (this.addGoodsForm.goods_cat.length < 3) {
        // 只允许选中三级分类
        this.$message.error('只允许选中三级分类')
        this.addGoodsForm.goods_cat = ''
      }
      // 要把字符串转成number
      this.addGoodsForm.goods_price = this.addGoodsForm.goods_price - 0
      this.addGoodsForm.goods_number = this.addGoodsForm.goods_number - 0
      this.addGoodsForm.goods_weight = this.addGoodsForm.goods_weight - 0
    },
    // 标签页切换之前的调用
    beforeTabLeave (activeName, oldActiveName) {
      // 清一下两边的空格
      this.addGoodsForm.goods_name = this.addGoodsForm.goods_name.trim()
      // handleChange()处做了处理，所以goods_cat这里是字符串，要转成数组才能.length
      // 条件：在第一个标签页，name不为空且.length=3
      // ||:有真就真，&&:有假就假
      if ((oldActiveName === '0') &&
        ((this.addGoodsForm.goods_name === '') ||
          (this.addGoodsForm.goods_cat.length !== 3))) {
        this.$message.error('请先完善商品信息')
        // return false 阻止标签页切换
        return false
      }
    },
    // 上传图片点击预览
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.previewImgDialogVisible = true
    },
    handleRemove (file, fileList) {
      const filePath = file.response.data.tmp_path
      // 将要删除的图片的临时路径
      const i =
        this.addGoodsForm.pics.findIndex(x =>
          x.pic === filePath
        )
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 监听图片上传成功的事件
    handleSuccess (response, file) {
      this.$message.success('图片上传成功')
      const picInfo = { pic: response.data.tmp_path }
      this.$message.success(response.meta.msg)
      this.addGoodsForm.pics.push(picInfo)
    },
    // 最后添加商品的按钮
    addGoods () {
      // 预校验
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        } else {
          // 深拷贝(不太懂)，不这样做大概意思就是'='号会改变原goods_cat的数据类型(如有错误请指正)
          const form = _.cloneDeep(this.addGoodsForm)
          form.goods_cat = form.goods_cat.join(',')
          // 处理addGoodsForm.attrs
          this.manyCateDate.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals.join(',') }
            this.addGoodsForm.attrs.push(newInfo)
          })
          this.onlyCateDate.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals }
            this.addGoodsForm.attrs.push(newInfo)
          })
          form.attrs = this.addGoodsForm.attrs
          const { data: res } = await this.$http.post('goods', form)
          if (res.meta.status === 201) {
            this.$message.success('商品添加成功！')
          } else {
            this.$message.error('商品添加失败' + res.meta.msg)
          }
          this.$router.push('/goods')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.el-dialog__body {
  padding: 0 !important;
}
.btnMarginTop {
  margin-top: 20px;
}
</style>
